<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>watch</title>
  </head>
  <body>
    <div id="app">
      {{ a }}
      {{ b }}
      {{ msg }}
      {{ user.firstName }}
      {{ user.lastName }}
    </div>

    <script src="../../dist/vue.js"></script>
    <script>
      const vm = new Vue({
        el: "#app",
        data: {
          a: "1",
          b: "2",
          msg: "Hello Vue",
          user: {
            firstName: "诸葛",
            lastName: "亮",
          },
        },
      });
      // expOrFn 是表达式
      vm.$watch('msg', function(newVal, oldVal) {
        console.log(newVal, oldVal)
      })
      vm.$watch('user.firstName', function(newVal, oldVal) {
        console.log(newVal, oldVal)
      })

      // expOrFn 是函数
      vm.$watch(function(){
        return this.a + this.b
      }, function(newVal, oldVal) {
        console.log(newVal, oldVal)
      })

      // deep 是 true，消耗性能
      vm.$watch('user', function(newVal, oldVal) {
        // 此时的 newVal 是 user 对象
        console.log(newVal === vm.user)
      }, { deep: true })

      // immediate 是 true
      vm.$watch('msg', function(newVal, oldVal) {
        console.log(newVal)
      }, { immediate: true })
    </script>
  </body>
</html>
